import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/image_utils.dart';

import '../../../message/message_config.dart';
import '../../../net/post_request.dart';
import '../../../net/response/food/regular_week_menu_list_data.dart';
import '../../../net/response/food/week_menu_list_data.dart';

class NewRegularWeekSubmitViewModel extends BaseViewModel {
  RegularWeekMenuListData menuData;
  final String oldId;
  final String sitId;
  final String time;
  final String orderModelType;
  final String useType;

  NewRegularWeekSubmitViewModel(BuildContext context,
      {required this.menuData,
      required this.oldId,
      required this.sitId,
      required this.time,
      required this.orderModelType,
      required this.useType})
      : super(context);

  var selectedMealList = <GoodsInfo>[];
  var totalPrice = 0.0;
  var oldPrice = 0.0;

  String remark = "";

  @override
  void onCreated() {
    super.onCreated();
    getSelectItem();
    notifyListeners();
  }

  void getSelectItem() {
    var listItems = menuData.menuJson?.content??[];
    selectedMealList.clear();
    totalPrice = 0.0;
    oldPrice = 0.0;
    for (var item in listItems) {
      for (GoodsInfo date in (item.goodsInfo ?? <GoodsInfo>[])) {
        for (var food in date.goodsList ?? <GoodsList>[]) {
          if (1 == food.oldStatus) {
            oldPrice += (food.price??0) * (food.oldNumber ?? 0);
          }
        }
        if (date.selectItems.isNotEmpty &&
            date.selectItems[0].canSelect &&
            1 != date.selectItems[0].isTake) {
          selectedMealList.add(date);

        }
        totalPrice += date.selectPrice();
      }
    }
    selectedMealList.sort((o1, o2) {
      return o1.weekDay!.compareTo(o2.weekDay!);
    });
  }

  Future<void> submitRequest() async {
    var listItems = menuData.menuJson?.content??[];
    var content = listItems.map((e) => e.toSubmitJson()).toList();
    showLoadingDialog(msg: '提交订单...');
    try {
      var data = await PostRequest.submitWeekOrder(
          menuData.menuId.toString(),
          menuData.menuJson?.weekMenuModel.toString(),
          sitId,
          oldId,
          time,
          orderModelType,
          remark,
          content,
          null,
          null,
          useType);
      hideDialog();
      if ('0' == data['code'].toString()) {
        var orderId = data['data']['id'].toString();
        await payOrder(orderId, (totalPrice - oldPrice).toString());
        // showToast('提交成功');
        // finish();
      } else {
        showToast(data['msg']);
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> payOrder(String orderId, String totalMoney) async {
    showLoadingDialog(msg: '正在完成支付...');
    try {
      var data = await PostRequest.weekPayOrder(
          orderId: orderId, type: "2", totalMoney: totalMoney);
      hideDialog();
      if ('0' == data['code'].toString()) {
        // showToast('支付成功');
        // sendMessage(SendMessageEvent(MessageConfig.PAY_FOOD_SUCCESS));
        // await _printTicket();
        // Go().pushRemoveUntil(page)
        showSuccessDialog();
      } else {
        showToast(data['msg']);
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  void showSuccessDialog() {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            content: Column(
              children: [
                Image.asset(ImageUtils.getImgPath("icon_success")),
                CommonText('支付成功')
              ],
            ),
            actions: [TextButton(onPressed: (){
              finish();
              finish();
              sendMessage(SendMessageEvent(MessageConfig.PAY_FOOD_SUCCESS));
            }, child: CommonText('关闭'))],
          );
        });
  }
}
